package server.gui.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.SwingUtilities;

import server.console.Consola;

public class ConsoleController {

	public static PrintStream getPrintStream(DefaultListModel<String> mensajes) {
		return new PrintStream(new ConsoleOutputStream(mensajes));
	}

	public static ActionListener getConsoleActionListener(JTextField field) {
		return new ConsoleActionListener(field);
	}

	public static MouseListener getConsoleListItemClick() {
		return new ConsoleListItemClick();
	}

	private static final class ConsoleOutputStream extends OutputStream {
		private DefaultListModel<String> mensajes;
		private StringBuilder sb;
		private PrintStream old;

		public ConsoleOutputStream(DefaultListModel<String> m) {
			this.sb = new StringBuilder();
			this.mensajes = m;
			this.old = System.out;
		}

		public void flush() {
		}

		public void close() {
		}

		public void write(int b) throws IOException {
			if (b == '\r')
				return;

			if (b == '\n') {
				final String text = sb.toString() + "\n";
				old.println(sb);
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						mensajes.addElement(text);
					}
				});
				sb.setLength(0);
				return;
			}
			final String n = new String(new byte[] { (byte) b },
					Charset.defaultCharset());
			sb.append(n);
		}
	}

	private static final class ConsoleActionListener implements ActionListener {
		JTextField textFieldComando;

		public ConsoleActionListener(JTextField field) {
			this.textFieldComando = field;
		}

		public void actionPerformed(ActionEvent arg0) {
			Consola.getInstance().ejecutar(textFieldComando.getText());
			textFieldComando.setText("");
		}
	}

	private static final class ConsoleListItemClick extends MouseAdapter {
		public void mouseClicked(MouseEvent evt) {
			if (evt.getClickCount() >= 1) {
				@SuppressWarnings("unchecked")
				JList<String> lista = (JList<String>) evt.getComponent();
				int indice = lista.getSelectedIndex();
				if (indice >= 0) {
					ListModel<String> listaModel = lista.getModel();
					String message = listaModel.getElementAt(indice);
					JOptionPane.showMessageDialog(null, message);
				}
			}
		}
	}
}